import React, { useState, useEffect } from 'react';
import { 
  Card, 
  Button, 
  Form, 
  Input, 
  message, 
  Avatar, 
  Typography, 
  Space,
  Divider,
  Modal
} from 'antd';
import { 
  UserOutlined, 
  EditOutlined, 
  LockOutlined, 
  LoginOutlined,
  ArrowLeftOutlined,
  CheckOutlined,
  CloseOutlined
} from '@ant-design/icons';
import { clientApi } from '../../services/api';
import { useNavigate } from 'react-router-dom';
import LoginModal from '../../components/LoginModal';
import { saveUser, getUser, removeUser } from '../../utils/auth';

const { Title, Text } = Typography;

const SettingsPage = () => {
  const navigate = useNavigate();
  const [user, setUser] = useState(getUser());
  const [loginVisible, setLoginVisible] = useState(false);
  const [nicknameForm] = Form.useForm();
  const [passwordForm] = Form.useForm();
  const [editingNickname, setEditingNickname] = useState(false);
  const [loading, setLoading] = useState(false);

  useEffect(() => {
    if (user) {
      nicknameForm.setFieldsValue({ nickname: user.nickname });
    }
  }, [user, nicknameForm]);

  const handleLogin = (userInfo) => {
    setUser(userInfo);
    saveUser(userInfo);
    setLoginVisible(false);
    message.success(`欢迎回来，${userInfo.nickname}！`);
  };

  const handleLogout = () => {
    Modal.confirm({
      title: '退出登录',
      content: '确定要退出登录吗？',
      centered: true,
      okText: '确定',
      cancelText: '取消',
      onOk: () => {
        setUser(null);
        removeUser();
        message.success('已退出登录');
        navigate('/');
      }
    });
  };

  const updateNickname = async (values) => {
    if (!user) return;
    
    setLoading(true);
    try {
      await clientApi.updateNickname(user.id, values.nickname);
      const updatedUser = { ...user, nickname: values.nickname };
      setUser(updatedUser);
      saveUser(updatedUser);
      message.success('昵称修改成功');
      setEditingNickname(false);
    } catch (error) {
      message.error(error.message || '修改失败');
    } finally {
      setLoading(false);
    }
  };

  const updatePassword = async (values) => {
    if (!user) return;
    
    if (values.newPassword !== values.confirmPassword) {
      message.error('两次输入的密码不一致');
      return;
    }

    setLoading(true);
    try {
      await clientApi.updatePassword(user.id, values.oldPassword, values.newPassword);
      message.success('密码修改成功');
      passwordForm.resetFields();
    } catch (error) {
      message.error(error.message || '修改失败');
    } finally {
      setLoading(false);
    }
  };

  const cancelNicknameEdit = () => {
    nicknameForm.resetFields();
    setEditingNickname(false);
  };

  if (!user) {
    return (
      <div style={{ background: 'var(--secondary-bg)', minHeight: '100vh' }}>
        {/* 顶部标题区域 */}
        <div style={{
          background: 'var(--primary-bg)',
          padding: '60px 20px 30px',
          textAlign: 'center',
          borderBottom: '1px solid var(--border-light)',
          position: 'relative'
        }}>
          <Button
            type="text"
            icon={<ArrowLeftOutlined />}
            onClick={() => navigate(-1)}
            style={{
              position: 'absolute',
              top: '20px',
              left: '20px',
              color: 'var(--text-tertiary)',
              fontSize: '18px',
              padding: '8px',
              borderRadius: '50%'
            }}
          />
          
          <Title level={2} style={{
            margin: 0,
            fontSize: '28px',
            fontWeight: 700,
            color: 'var(--text-primary)',
            lineHeight: 1.2
          }}>
            设置
          </Title>
          <Text style={{
            color: 'var(--text-secondary)',
            fontSize: '16px',
            marginTop: '8px',
            display: 'block'
          }}>
            管理您的账户设置
          </Text>
        </div>

        <div style={{ padding: '40px 20px', textAlign: 'center' }}>
          <Avatar
            size={80}
            icon={<UserOutlined />}
            style={{
              background: 'var(--tertiary-bg)',
              color: 'var(--text-tertiary)',
              marginBottom: '20px'
            }}
          />
          <Title level={3} style={{ color: 'var(--text-primary)', marginBottom: '8px' }}>
            请先登录
          </Title>
          <Text style={{ color: 'var(--text-secondary)', marginBottom: '24px', display: 'block' }}>
            登录后可以使用完整功能
          </Text>
          <Button
            type="primary"
            icon={<LoginOutlined />}
            onClick={() => setLoginVisible(true)}
            style={{
              background: 'var(--accent-primary)',
              borderColor: 'var(--accent-primary)',
              borderRadius: '25px',
              height: '48px',
              padding: '0 32px',
              fontSize: '16px',
              fontWeight: 500
            }}
          >
            立即登录
          </Button>
        </div>

        <LoginModal
          visible={loginVisible}
          onCancel={() => setLoginVisible(false)}
          onSuccess={handleLogin}
        />
      </div>
    );
  }

  return (
    <div style={{ background: 'var(--secondary-bg)', minHeight: '100vh' }}>
      {/* 顶部标题区域 */}
      <div style={{
        background: 'var(--primary-bg)',
        padding: '60px 20px 30px',
        textAlign: 'center',
        borderBottom: '1px solid var(--border-light)',
        position: 'relative'
      }}>
        <Button
          type="text"
          icon={<ArrowLeftOutlined />}
          onClick={() => navigate(-1)}
          style={{
            position: 'absolute',
            top: '20px',
            left: '20px',
            color: 'var(--text-tertiary)',
            fontSize: '18px',
            padding: '8px',
            borderRadius: '50%'
          }}
        />
        
        <Title level={2} style={{
          margin: 0,
          fontSize: '28px',
          fontWeight: 700,
          color: 'var(--text-primary)',
          lineHeight: 1.2
        }}>
          设置
        </Title>
        <Text style={{
          color: 'var(--text-secondary)',
          fontSize: '16px',
          marginTop: '8px',
          display: 'block'
        }}>
          管理您的账户设置
        </Text>
      </div>

      <div style={{ padding: '20px' }}>
        {/* 用户信息卡片 */}
        <Card style={{
          borderRadius: '20px',
          marginBottom: '20px',
          boxShadow: 'var(--shadow-medium)',
          border: 'none'
        }}>
          <div style={{ textAlign: 'center', padding: '20px 0' }}>
            <Avatar
              size={64}
              icon={<UserOutlined />}
              style={{
                background: 'var(--accent-primary)',
                color: '#fff',
                marginBottom: '16px'
              }}
            />
            <Title level={4} style={{ margin: 0, color: 'var(--text-primary)' }}>
              {user.nickname}
            </Title>
            <Text style={{ color: 'var(--text-secondary)', fontSize: '14px' }}>
              用户ID: {user.id}
            </Text>
          </div>
        </Card>

        {/* 昵称设置 */}
        <Card style={{
          borderRadius: '20px',
          marginBottom: '20px',
          boxShadow: 'var(--shadow-medium)',
          border: 'none'
        }}>
          <Title level={4} style={{ margin: '0 0 20px 0', color: 'var(--text-primary)' }}>
            修改昵称
          </Title>
          <Form
            form={nicknameForm}
            onFinish={updateNickname}
            layout="vertical"
            style={{ marginBottom: 0 }}
          >
            <Form.Item
              name="nickname"
              rules={[
                { required: true, message: '请输入昵称' },
                { min: 2, max: 20, message: '昵称长度在2-20个字符之间' }
              ]}
              style={{ marginBottom: 16 }}
            >
              <Input
                placeholder="请输入新昵称"
                size="large"
                style={{
                  borderRadius: '12px',
                  border: '1px solid var(--border-light)',
                  background: 'var(--primary-bg)'
                }}
                disabled={!editingNickname}
              />
            </Form.Item>
            
            <div style={{ display: 'flex', gap: '8px' }}>
              {editingNickname ? (
                <>
                  <Button
                    type="primary"
                    htmlType="submit"
                    loading={loading}
                    icon={<CheckOutlined />}
                    style={{
                      flex: 1,
                      borderRadius: '12px',
                      height: '44px'
                    }}
                  >
                    保存
                  </Button>
                  <Button
                    onClick={cancelNicknameEdit}
                    icon={<CloseOutlined />}
                    style={{
                      flex: 1,
                      borderRadius: '12px',
                      height: '44px'
                    }}
                  >
                    取消
                  </Button>
                </>
              ) : (
                <Button
                  type="primary"
                  icon={<EditOutlined />}
                  onClick={() => setEditingNickname(true)}
                  style={{
                    flex: 1,
                    borderRadius: '12px',
                    height: '44px'
                  }}
                >
                  修改昵称
                </Button>
              )}
            </div>
          </Form>
        </Card>

        {/* 密码设置 */}
        <Card style={{
          borderRadius: '20px',
          marginBottom: '20px',
          boxShadow: 'var(--shadow-medium)',
          border: 'none'
        }}>
          <Title level={4} style={{ margin: '0 0 20px 0', color: 'var(--text-primary)' }}>
            修改密码
          </Title>
          <Form
            form={passwordForm}
            onFinish={updatePassword}
            layout="vertical"
            style={{ marginBottom: 0 }}
          >
            <Form.Item
              name="oldPassword"
              rules={[{ required: true, message: '请输入原密码' }]}
              style={{ marginBottom: 16 }}
            >
              <Input.Password
                placeholder="请输入原密码"
                size="large"
                style={{
                  borderRadius: '12px',
                  border: '1px solid var(--border-light)',
                  background: 'var(--primary-bg)'
                }}
              />
            </Form.Item>
            
            <Form.Item
              name="newPassword"
              rules={[
                { required: true, message: '请输入新密码' },
                { min: 6, message: '密码长度至少6位' }
              ]}
              style={{ marginBottom: 16 }}
            >
              <Input.Password
                placeholder="请输入新密码"
                size="large"
                style={{
                  borderRadius: '12px',
                  border: '1px solid var(--border-light)',
                  background: 'var(--primary-bg)'
                }}
              />
            </Form.Item>
            
            <Form.Item
              name="confirmPassword"
              rules={[
                { required: true, message: '请确认新密码' },
                ({ getFieldValue }) => ({
                  validator(_, value) {
                    if (!value || getFieldValue('newPassword') === value) {
                      return Promise.resolve();
                    }
                    return Promise.reject(new Error('两次输入的密码不一致'));
                  },
                })
              ]}
              style={{ marginBottom: 20 }}
            >
              <Input.Password
                placeholder="请确认新密码"
                size="large"
                style={{
                  borderRadius: '12px',
                  border: '1px solid var(--border-light)',
                  background: 'var(--primary-bg)'
                }}
              />
            </Form.Item>
            
            <Form.Item style={{ marginBottom: 0 }}>
              <Button
                type="primary"
                htmlType="submit"
                loading={loading}
                icon={<LockOutlined />}
                style={{
                  width: '100%',
                  borderRadius: '12px',
                  height: '44px'
                }}
              >
                修改密码
              </Button>
            </Form.Item>
          </Form>
        </Card>

        {/* 退出登录 */}
        <Button
          type="default"
          danger
          onClick={handleLogout}
          icon={<LoginOutlined />}
          style={{
            width: '100%',
            borderRadius: '12px',
            height: '48px',
            fontSize: '16px',
            fontWeight: 500
          }}
        >
          退出登录
        </Button>
      </div>

      <LoginModal
        visible={loginVisible}
        onCancel={() => setLoginVisible(false)}
        onSuccess={handleLogin}
      />
    </div>
  );
};

export default SettingsPage;